<?php
session_start();
require_once '../../database/config.php';
require_once '../../export.php';

class question
{
    /**
     * 获取试题列表信息（分页提取）
     * param: pageIndex（当前页码）
     * param: pageSize（每页记录数）
     * param：username（查询条件用户名）
     * param：usersex（查询条件性别）
     * param：usertel（查询条件联系电话）
     */
    function getQuestionListByPage($pageIndex, $pageSize, $questiontitle, $questioncourse, $classify, $questiontype, $difficulty)
    {
        $sql = "select question.id,typeid,case typeid when 1 then '判断题' when 2 then '单项选择题' when 3 then '多项选择题'
                end as typename,questiontitle,questioncourse,case questioncourse when 1 then '科目一' when 2 then '科目四' end as questioncourseText,
                question.classifyid,classifyname,difficulty,case difficulty when 1 then '简单' when 2 then '中等' when 3 then '困难'end as difficultyText,
                question.inputdate from question join classify on classify.classifyid = question.classifyid WHERE 1=1 ";
        if ($questiontitle != "") {
            $sql = $sql . " and questiontitle like '%$questiontitle%'";
        }
        if ($questioncourse != "") {
            $sql = $sql . " and questioncourse = '$questioncourse'";
        }
        if ($classify != "") {
            $sql = $sql . " and question.classifyid = '$classify'";
        }
        if ($questiontype != "") {
            $sql = $sql . " and typeid ='$questiontype'";
        }
        if ($difficulty != "") {
            $sql = $sql . " and difficulty = $difficulty";
        }
        $count = $this->getQuestionListCount($sql);
        $startno = ($pageIndex - 1) * $pageSize;
        $sql = $sql . " order by inputdate desc limit $startno," . $pageSize;
        $result = $GLOBALS['conn']->query($sql);
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $questionList = array();
        while ($row = $result->fetch()) {
            $questionList[] = $row;
        }
        $result = array(
            "code" => 0,
            "count" => $count,
//            "msg" => "success",
            "list" => $questionList
        );
        echo json_encode($result);
    }
    /**
     * 获取记录总数（用于实现分页查询）
     * param: sql（查询语句）
     */
    function getQuestionListCount($sql)
    {
        $result = $GLOBALS['conn']->query($sql);
        return $result->rowCount();
    }
    /**
     * 获取所有试题归类
     */
    function getClassify()
    {
        $result = $GLOBALS['conn']->query("select classifyid,classifyname from classify");
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $classifyList = array();
        while ($row = $result->fetch()) {
            $classifyList[] = $row;
        }
        echo json_encode($classifyList);
    }
    /**
     * 试题添加
     * param： id（试题编号）
     * param： questiontitle（试题标题）
     * param： questioncourse（试题科目）
     * param： typeid（试题类型）
     * param： classifyid（试题归类）
     * param： difficulty（试题难易度）
     * param： question（试题内容）
     * param： answer（试题答案）
     * param： choicea（试题答案选项A）
     * param： choiceb（试题答案选项B）
     * param： choicec（试题答案选项C）
     * param： choiced（试题答案选项D）
     * param： analysis（试题解析）
     */
    function addQuestion($questiontitle,$questioncourse,$typeid,$classifyid,$difficulty,$question,$answer,$choicea,$choiceb,$choicec,$choiced,$analysis)
    {
        $uploadresult = $this->uploadFile();
        if ($uploadresult['code'] == 0){
            $imginfo = $uploadresult['path'];

            $stmt = $GLOBALS['conn']->prepare("insert into question(typeid,questiontitle,questioncourse,question,classifyid,answer,
                                              difficulty,choicea,choiceb,choicec,choiced,analysis,imginfo,inputdate)
                                              values(:typeid,:questiontitle,:questioncourse,:question,:classifyid,:answer,:difficulty,
                                              :choicea,:choiceb,:choicec,:choiced,:analysis,:imginfo,now())");

            $stmt->bindParam("questiontitle", $questiontitle);
            $stmt->bindParam("questioncourse", $questioncourse);
            $stmt->bindParam("typeid", $typeid);
            $stmt->bindParam("classifyid", $classifyid);
            $stmt->bindParam("difficulty", $difficulty);
            $stmt->bindParam("question", $question);
            $stmt->bindParam("answer", $answer);
            $stmt->bindParam("choicea", $choicea);
            $stmt->bindParam("choiceb", $choiceb);
            $stmt->bindParam("choicec", $choicec);
            $stmt->bindParam("choiced", $choiced);
            $stmt->bindParam("analysis", $analysis);
            $stmt->bindParam("imginfo", $imginfo);

            $rs = $stmt->execute();
            if ($rs) {
                $sql = "select question.id,typeid,case typeid when 1 then '判断题' when 2 then '单项选择题' when 3 then '多项选择题'
                end as typename,questiontitle,questioncourse,case questioncourse when 1 then '科目一' when 2 then '科目四' end as questioncourseText,
                question.classifyid,classifyname,difficulty,case difficulty when 1 then '简单' when 2 then '中等' when 3 then '困难'end as difficultyText,
                question.inputdate from question join classify on classify.classifyid = question.classifyid WHERE question.id in ( select last_insert_id()) ";
                $result = $GLOBALS['conn']->query($sql);
                $result->setFetchMode(PDO::FETCH_ASSOC);
                $insertrec = array();
                while ($row = $result->fetch()) {
                    $insertrec[] = $row;
                }
                $result = array("msg" => "操作成功", "code" => 0, "insertrec"=>$insertrec);
            } else {
                $result = array("msg" => "操作失败", "code" => 1);
            }
            echo json_encode($result);
        }else{
            $result = array(
                "code" => -1,
                "msg" => $uploadresult['msg']
            );
            echo json_encode($result);
        }
    }
    /**
     * 试题修改（参数说明见试题添加）
     */
    function updateQuestion($id,$questiontitle,$questioncourse,$typeid,$classifyid,$difficulty,$question,$answer,$choicea,$choiceb,$choicec,$choiced,$analysis)
    {
        $uploadresult = $this->uploadFile();
        if ($uploadresult['code'] == 0){
            $imginfo = $uploadresult['path'];
            if ($imginfo == ""){
                $stmt = $GLOBALS['conn']->prepare("update question set questiontitle=:questiontitle,questioncourse=:questioncourse,typeid=:typeid,
                                                    classifyid=:classifyid,difficulty=:difficulty,question=:question,answer=:answer,choicea=:choicea,
                                                    choiceb=:choiceb,choicec=:choicec,choiced=:choiced,analysis=:analysis where id=:id");
                $stmt->bindParam("questiontitle", $questiontitle);
                $stmt->bindParam("questioncourse", $questioncourse);
                $stmt->bindParam("typeid", $typeid);
                $stmt->bindParam("classifyid", $classifyid);
                $stmt->bindParam("difficulty", $difficulty);
                $stmt->bindParam("question", $question);
                $stmt->bindParam("answer", $answer);
                $stmt->bindParam("choicea", $choicea);
                $stmt->bindParam("choiceb", $choiceb);
                $stmt->bindParam("choicec", $choicec);
                $stmt->bindParam("choiced", $choiced);
                $stmt->bindParam("analysis", $analysis);
                $stmt->bindParam("id", $id);
            }else{
                $stmt = $GLOBALS['conn']->prepare("update question set questiontitle=:questiontitle,questioncourse=:questioncourse,typeid=:typeid,
                                                    classifyid=:classifyid,difficulty=:difficulty,question=:question,answer=:answer,choicea=:choicea,
                                                    choiceb=:choiceb,choicec=:choicec,choiced=:choiced,analysis=:analysis,imginfo=:imginfo where id=:id");
                $stmt->bindParam("questiontitle", $questiontitle);
                $stmt->bindParam("questioncourse", $questioncourse);
                $stmt->bindParam("typeid", $typeid);
                $stmt->bindParam("classifyid", $classifyid);
                $stmt->bindParam("difficulty", $difficulty);
                $stmt->bindParam("question", $question);
                $stmt->bindParam("answer", $answer);
                $stmt->bindParam("choicea", $choicea);
                $stmt->bindParam("choiceb", $choiceb);
                $stmt->bindParam("choicec", $choicec);
                $stmt->bindParam("choiced", $choiced);
                $stmt->bindParam("analysis", $analysis);
                $stmt->bindParam("imginfo", $imginfo);
                $stmt->bindParam("id", $id);
            }
            $rs = $stmt->execute();
            if ($rs) {
                $sql = "select question.id,typeid,case typeid when 1 then '判断题' when 2 then '单项选择题' when 3 then '多项选择题'
                end as typename,questiontitle,questioncourse,case questioncourse when 1 then '科目一' when 2 then '科目四' end as questioncourseText,
                question.classifyid,classifyname,difficulty,case difficulty when 1 then '简单' when 2 then '中等' when 3 then '困难'end as difficultyText,
                question.inputdate from question join classify on classify.classifyid = question.classifyid WHERE question.id = $id ";
                $result = $GLOBALS['conn']->query($sql);
                $result->setFetchMode(PDO::FETCH_ASSOC);
                $editrec = array();
                while ($row = $result->fetch()) {
                    $editrec[] = $row;
                }
                $result = array("msg" => "操作成功", "code" => 0, "editrec"=>$editrec);
            } else {
                $result = array("msg" => "操作失败", "code" => 1);
            }
            echo json_encode($result);
        }else{
            $result = array(
                "code" => -1,
                "msg" => $uploadresult['msg']
            );
            echo json_encode($result);
        }
    }
    /**
     * 根据试题编号获取试题信息
     * param：id（试题编号）
     */
    function getQuestionById($id){
        $stmt = $GLOBALS['conn']->prepare("select question.id,typeid,case typeid when 1 then '判断题' when 2 then '单项选择题' when 3 then '多项选择题'
                end as typename,questiontitle,questioncourse,case questioncourse when 1 then '科目一' when 2 then '科目四' end as questioncourseText,question,answer,
                question.classifyid,classifyname,difficulty,case difficulty when 1 then '简单' when 2 then '中等' when 3 then '困难'end as difficultyText,analysis,
                choicea,choiceb,choicec,choiced,question.inputdate,imginfo from question join classify on classify.classifyid = question.classifyid WHERE question.id=:id ");
        $stmt->bindParam('id', $id);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $result = array();
        if ($rows = $stmt->fetch()){
            $result[] = $rows;
        }
        echo json_encode($result);
    }
    /**
     * 删除试题
     * param：id（试题编号）
     */
    function deleteQuestion($id){
        $stmt = $GLOBALS['conn']->prepare("delete from question where id=:id");
        $stmt->bindParam("id", $id);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            $result = array("msg" => "操作成功", "errorCode" => 0);
        } else {
            $result = array("msg" => "操作失败", "errorCode" => 1);
        }
        echo json_encode($result);
    }
    /**
     * 文件上传
     */
    function uploadFile()
    {
        if ($_FILES["file"]["name"] != null){
            $allowedExts = array("gif", "jpeg", "jpg", "png");
            $temp = explode(".", $_FILES["file"]["name"]);
            $extension = strtolower(end($temp));        // 获取文件后缀名
            if (in_array($extension, $allowedExts)){
                if ($_FILES["file"]["error"] > 0)
                {
                    return array("code"=>-1,"msg"=>"图片上传失败","path"=>"");
                }
                else
                {
                    $filename = time().md5(uniqid(mt_rand(), true)).'.'.$extension;
                    move_uploaded_file($_FILES["file"]["tmp_name"],
                        "../../upload/".$filename);
                    return array("code"=>0,"msg"=>"图片上传成功","path"=>'upload/'.$filename);
                }
            }
            else
            {
                return array("code"=>-1,"msg"=>"图片上传失败","path"=>"");
            }
        }else{
            return array("code"=>0,"msg"=>"没有上传图片","path"=> "");
        }

    }
    /**
     * 数据导出
     */
    function export(){
        $export = new Export();
        $result = $GLOBALS['conn']->query("select question.id,case typeid when 1 then '判断题' when 2 then '单项选择题' when 3 then '多项选择题'
                end as typename,questiontitle,case questioncourse when 1 then '科目一' when 2 then '科目四' end as questioncourseText,question,answer,
                classifyname,case difficulty when 1 then '简单' when 2 then '中等' when 3 then '困难'end as difficultyText,analysis,
                choicea,choiceb,choicec,choiced,question.inputdate from question join classify on classify.classifyid = question.classifyid");
        $data = array();
        $result->setFetchMode(PDO::FETCH_ASSOC);
        while ($row = $result->fetch()) {
            $data[] = $row;
        }
        if(count($data) > 0){
            $fields = array_keys($data[0]);
            $export->addHeader($fields);
            $export->addBody($data);
            $export->downLoad();
        } else{
            echo "<script>history.back();</script>";
        }
    }
}
$question = new question();
$method = $_POST['method'];
if ($method == "getQuestionListByPage") {
    $pageIndex = $_POST['pageIndex'];
    $pageSize = $_POST['pageSize'];
    $questiontitle = $_POST['questiontitle'];
    $questioncourse = $_POST['questioncourse'];
    $classify = $_POST['classify'];
    $questiontype = $_POST['questiontype'];
    $difficulty = $_POST['difficulty'];
    $question->getQuestionListByPage($pageIndex, $pageSize, $questiontitle, $questioncourse, $classify, $questiontype, $difficulty);
}
if ($method == "getClassify") {
    $question->getClassify();
}
if ($method == "addQuestion") {
    $questiontitle = $_POST['questiontitle'];
    $questioncourse = $_POST['questioncourse'];
    $typeid = $_POST['questiontype'];
    $classifyid = $_POST['classify'];
    $difficulty = $_POST['difficulty'];

    $qst = $_POST['question'];
    $answer = '';
    if ($typeid != 3){
        $answer = $_POST['ranswer'];
    }else{
        $answerlist = $_POST['canswer'];
        foreach ($answerlist as $list){
            $answer = $answer . $list . ',';
        }
        $answer = substr($answer,0,strlen($answer)-1);
    }

    $choicea = $_POST['choicea'];
    $choiceb = $_POST['choiceb'];
    $choicec = $_POST['choicec'];
    $choiced = $_POST['choiced'];
    $analysis = $_POST['analysis'];
    $question->addQuestion($questiontitle,$questioncourse,$typeid,$classifyid,$difficulty,$qst,$answer,$choicea,$choiceb,$choicec,$choiced,$analysis);
}
if ($method == "updateQuestion") {
    $questiontitle = $_POST['questiontitle'];
    $questioncourse = $_POST['questioncourse'];
    $typeid = $_POST['questiontype'];
    $classifyid = $_POST['classify'];
    $difficulty = $_POST['difficulty'];
    $qst = $_POST['question'];
    $answer = '';
    if ($typeid != 3){
        $answer = $_POST['ranswer'];
    }else{
        $answerlist = $_POST['canswer'];
        foreach ($answerlist as $list){
            $answer = $answer . $list . ',';
        }
        $answer = substr($answer,0,strlen($answer)-1);
    }
    $id = $_POST['id'];
    $choicea = $_POST['choicea'];
    $choiceb = $_POST['choiceb'];
    $choicec = $_POST['choicec'];
    $choiced = $_POST['choiced'];
    $analysis = $_POST['analysis'];
    $question->updateQuestion($id,$questiontitle,$questioncourse,$typeid,$classifyid,$difficulty,$qst,$answer,$choicea,$choiceb,$choicec,$choiced,$analysis);
}
if ($method == "deleteQuestion") {
    $id = $_POST['id'];
    $question->deleteQuestion($id);
}
if ($method == "getQuestionById") {
    $id = $_POST['id'];
    $question->getQuestionById($id);
}
$export = $_GET['export'];
if ($export == "export") {
    $question->export();
}
?>